//
//  UploadFileInfo.swift
//  App
//
//  Created by 汤泽川 on 2019/3/30.
//

import Vapor
import FileUtils

struct UploadFileRequest : Content{
    var file : Core.File
    var fileType : String
}

struct UploadFileResponse : Content {
    var url : String
}

extension Core.File {
    public func saveTo(path : String, typeName : String) throws -> String {
        let fileFolderPath = path.hasSuffix("/") ? path : path + "/"
        let typeName = typeName.hasPrefix(".") ? typeName : "." + typeName
        let fileName = self.data.sha1.hexEncodedString()
        if Path.exists(fileFolderPath) == false {
            if Directory.create(atPath: fileFolderPath, recursion : true) == false {
                print("create folder error")
            }
        }
        if FileUtils.File.exists(fileFolderPath + fileName + typeName) == false {
            try self.data.write(to: URL(fileURLWithPath: fileFolderPath + fileName + typeName))
        }
        return fileName + typeName
    }
}

extension FileUtils.Directory {
    public static func create(atPath path: String, recursion : Bool) -> Bool {
        if recursion == false {
            return create(atPath: path)
        }
        let pathComponents = path.components(separatedBy: "/")
        var currentPath = ""
        for pathComponent in pathComponents {
            currentPath = currentPath + "/" + pathComponent
            let result = Path.exists(currentPath) ? true : Directory.create(atPath: currentPath)
            if result == false {
                return result
            }
        }
        return true
    }
}
